﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Kurogane.Buildin;

namespace Kurogane.Runtime {
	public class Scope {

		private readonly Scope _parent;
		private readonly IDictionary<string, object> _values = new Dictionary<string, object>();

		public Scope() : this(null) {

		}

		public Scope(Scope parent) {
			_parent = parent;
		}

		public bool HasVariable(string name) {
			return _values.ContainsKey(name);
		}

		public object GetVariable(string name) {
			if (_values.ContainsKey(name)) {
				return _values[name];
			}
			else if (_parent != null){
				return _parent.GetVariable(name);
			}
			throw new KrgnException(String.Format("変数「{0}」が存在しません。", name)); ;
		}

		public void SetVariable(string name, object value) {
			_values[name] = value;
		}
	}

	public class ScopeAccessor {

		public readonly string _name;
		public readonly Scope _scope;
		
		public ScopeAccessor(string name, Scope scope) {
			_name = name;
			_scope = scope;
		}

		public object Get() {
			return _scope.GetVariable(_name);
		}

		public void Set(object value) {
			_scope.SetVariable(_name, value);
		}
	}
}
